package com.itheima.order.transListener;

import com.alibaba.fastjson.JSON;
import com.itheima.order.entity.OrderEntity;
import com.itheima.order.mapper.OrderMapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RocketMQTransactionListener
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    //执行本地事务
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        byte[] info = (byte[]) msg.getPayload();
        System.out.println("receive trans message : "+new String(info));
        //解析消息
        OrderEntity orderEntity = JSON.parseObject(new String(info), OrderEntity.class);

        //删除订单
        orderEntity.setIsDel(1);
        int result = orderMapper.updateById(orderEntity);
        if (result >=1){
            /**
             * 事务消息状态有三种：
             * COMMIT：提交事务，消费者会立即接收到消息
             * ROLLBACK：回滚事务，消费方不会接收到消息
             * UNKNOWN：中间状态，需要进行本地事务回查
             */

            //模拟演示事务回查
            try {
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    //事务回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {

        byte[] info = (byte[]) msg.getPayload();
        System.out.println("receive trans message : "+new String(info));
        //解析消息
        OrderEntity orderEntity = JSON.parseObject(new String(info), OrderEntity.class);

        int isDel = orderMapper.selectById(orderEntity.getId()).getIsDel();
        if (isDel == 1){
            return RocketMQLocalTransactionState.COMMIT;
        }else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
